package com.ebelter.bpm.activitys;


import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.ebelter.bpm.R;
import com.ebelter.btcomlib.bases.activity.BaseActivity;
import com.ebelter.btcomlib.models.https.NetUtils;
import com.ebelter.btcomlib.models.https.interfaces.HttpResponse;
import com.ebelter.btcomlib.models.https.responses.GetBloodPressureData2;
import com.ebelter.btcomlib.utils.StringUtils;
import com.ebelter.btcomlib.utils.TimeUtils;
import com.ebelter.btcomlib.utils.ToastUtil;
import com.ebelter.btcomlib.utils.ViewUtils;
import com.ebelter.btcomlib.utils.log.LogUtils;
import com.ebelter.btcomlib.views.ChartView;
import com.ebelter.btcomlib.views.dialogs.otherpick.TianCiPickDialog;

import com.ebelter.btcomlib.views.dialogs.picktime.OnSureLisener;
import com.ebelter.btcomlib.views.dialogs.picktime2.CustomDatePicker;


import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;


/**
 * 血压曲线界面
 */
public class BPM_BloodPressureCurveActivity extends BaseActivity implements View.OnClickListener {

    public static final String TAG = "BPM_BloodPressureCurveActivity";


    TextView topTitleTv;

    TextView top_tianci_tv;//顶部左边的 天 和 次 按钮
    TextView top_right_ci_tv;//顶部右边 单个时间
    TextView top_right_tian_2_tv;//顶部右边 双个时间 1选择器
    TextView top_right_tian_4_tv;//顶部右边 双个时间 2选择器
    LinearLayout top_right_tian_ll;////顶部右边 双个时间 总布局




    private ChartView chartview_ss_sz;
    private ChartView chartview_maibo;

    //--------------------------------------------表格1
    TextView shsy_min_tv;
    TextView shsy_max_tv;
    TextView shsy_avg_tv;
    ImageView shsy_qushi_iv;


    TextView shzhy_min_tv;
    TextView shzhy_max_tv;
    TextView shzhy_avg_tv;
    ImageView shzhy_qushi_iv;

    TextView maibo_min_tv;
    TextView maibo_max_tv;
    TextView maibo_avg_tv;
    ImageView maibo_qushi_iv;


    private static final String NON = "";
    private void disExtendValues(String shsy_min,String shsy_max,String shsy_avg,
                                 String shzhy_min,String shzhy_max,String shzhy_avg,
                                 String maibo_min,String maibo_max,String maibo_avg){

        ViewUtils.setTextViewStr(shsy_min_tv,shsy_min);
        ViewUtils.setTextViewStr(shsy_max_tv,shsy_max);
        ViewUtils.setTextViewStr(shsy_avg_tv,shsy_avg);

        ViewUtils.setTextViewStr(shzhy_min_tv,shzhy_min);
        ViewUtils.setTextViewStr(shzhy_max_tv,shzhy_max);
        ViewUtils.setTextViewStr(shzhy_avg_tv,shzhy_avg);

        ViewUtils.setTextViewStr(maibo_min_tv,maibo_min);
        ViewUtils.setTextViewStr(maibo_max_tv,maibo_max);
        ViewUtils.setTextViewStr(maibo_avg_tv,maibo_avg);

    }
    private void extendValues2Non(){
        disExtendValues(NON,NON,NON,NON,NON,NON,NON,NON,NON);
    }

    private void clearArrowIv(){
        if (shsy_qushi_iv!=null) shsy_qushi_iv.setImageResource(0);
        if (shzhy_qushi_iv!=null) shzhy_qushi_iv.setImageResource(0);
        if (maibo_qushi_iv!=null) maibo_qushi_iv.setImageResource(0);
    }

    //--------------------------------------------表格2


    //当前显示的类型 0代表天 1代表次
    private int currentDisplayStyle;

    private String time_ci_1_str;
    private String time_tian_1_str;
    private String time_tian_2_str;

    @Override
    protected int loadLayoutById() {
        return R.layout.activity_bpm_blood_presssure_curve;
    }

    @Override
    protected void initView() {
        if (!NetUtils.available()){
            ToastUtil.show(R.string.Network_error);
        }
        FV();

        initTimes();

        updateTopLayout();

        setListeners();

        getDataFromNet();
    }

    //初始化时间
    private void initTimes() {
        String today = TimeUtils.getTodayZeroTime(-1,false);
        String tomorrow = TimeUtils.getTodayZeroTime(0,false);
        time_ci_1_str=tomorrow;
        time_tian_1_str=today;
        time_tian_2_str=tomorrow;
        ViewUtils.setTextViewStr(top_right_ci_tv,TimeUtils.formatDateStampString0(this,TimeUtils.parseFormatter3Time(time_ci_1_str).getTime()));
        ViewUtils.setTextViewStr(top_right_tian_2_tv,TimeUtils.formatDateStampString0(this,TimeUtils.parseFormatter3Time(time_tian_1_str).getTime()));
        ViewUtils.setTextViewStr(top_right_tian_4_tv,TimeUtils.formatDateStampString0(this,TimeUtils.parseFormatter3Time(time_tian_2_str).getTime()));

    }

    //设置点击监听器
    private void setListeners() {
        top_tianci_tv.setOnClickListener(this);
        top_right_ci_tv.setOnClickListener(this);
        top_right_tian_2_tv.setOnClickListener(this);
        top_right_tian_4_tv.setOnClickListener(this);
    }


    //更新显示顶部布局
    private void updateTopLayout() {
        if (currentDisplayStyle==0){
            ViewUtils.setTextViewStr(top_tianci_tv,getString(R.string.tian));
            ViewUtils.displayView(top_right_tian_ll);
            ViewUtils.goneView(top_right_ci_tv);
            if (chartview_ss_sz!=null){
                chartview_ss_sz.isDisplayXDateFlag=true;
                chartview_ss_sz.invalidate();
            }
            if (chartview_maibo!=null) {
                chartview_maibo.isDisplayXDateFlag = true;
                chartview_maibo.invalidate();
            }

        }else if (currentDisplayStyle==1){
            ViewUtils.setTextViewStr(top_tianci_tv,getString(R.string.ci));
            ViewUtils.goneView(top_right_tian_ll);
            ViewUtils.displayView(top_right_ci_tv);
            if (chartview_ss_sz!=null){
                chartview_ss_sz.isDisplayXDateFlag=false;
                chartview_ss_sz.invalidate();
            }
            if (chartview_maibo!=null) {
                chartview_maibo.isDisplayXDateFlag = false;
                chartview_maibo.invalidate();
            }
        }
    }

    private void FV() {
        topTitleTv = findViewById(R.id.top_title_tv);

        top_tianci_tv = findViewById(R.id.top_tianci_tv);
        top_right_ci_tv = findViewById(R.id.top_right_ci_tv);
        top_right_tian_2_tv = findViewById(R.id.top_right_tian_2_tv);
        top_right_tian_4_tv = findViewById(R.id.top_right_tian_4_tv);
        top_right_tian_ll = findViewById(R.id.top_right_tian_ll);

        shsy_min_tv = findViewById(R.id.shsy_min_tv);
        shsy_max_tv = findViewById(R.id.shsy_max_tv);
        shsy_avg_tv = findViewById(R.id.shsy_avg_tv);
        shsy_qushi_iv = findViewById(R.id.shsy_qushi_iv);

        maibo_min_tv = findViewById(R.id.maibo_min_tv);
        maibo_max_tv = findViewById(R.id.maibo_max_tv);
        maibo_avg_tv = findViewById(R.id.maibo_avg_tv);
        maibo_qushi_iv = findViewById(R.id.maibo_qushi_iv);

        shzhy_min_tv = findViewById(R.id.shzhy_min_tv);
        shzhy_max_tv = findViewById(R.id.shzhy_max_tv);
        shzhy_avg_tv = findViewById(R.id.shzhy_avg_tv);
        shzhy_qushi_iv = findViewById(R.id.shzhy_qushi_iv);

        chartview_ss_sz = findViewById(R.id.chartview_ss_sz);
        chartview_maibo = findViewById(R.id.chartview_maibo);


    }

    @Override
    protected void initData() {
        topTitleTv.setText(R.string.xueyaquxian);


    }

    //返回键被按下
    public void backClick(View view) {
        LogUtils.i(TAG, "返回键被按下");
        finish();
    }


    //history键被按下
    public void historyClick(View view) {
        LogUtils.i(TAG, "historyClick");
        startActivity(BPM_HistoryActivity.class);
    }


    @Override
    public void onClick(View v) {


        int id=v.getId();
        if (id==R.id.top_tianci_tv){//顶部的左边天和次按钮文本

            showTianCiDialog();

        }else if (id==R.id.top_right_ci_tv){//顶部右边单时间选择器

            showDataDialog(1);
        }else if (id==R.id.top_right_tian_2_tv){//顶部右边双时间选择器中的1选择器
            showDataDialog(2);
        }else if (id==R.id.top_right_tian_4_tv){//顶部右边单时间选择器中的2选择器
            showDataDialog(3);
        }



    }

    //展示时间选择器 1-次1   2-天1  3-天2
    private void showDataDialog(final int i) {

        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm", Locale.CHINA);
        String time = sdf.format(new Date());
        String date = time.split(" ")[0];
        CustomDatePicker datePicker= new CustomDatePicker(this,new CustomDatePicker.ResultHandler() {
            @Override
            public void handle(String time) {
                //currentDate.setText(time.split(" ")[0]);
                LogUtils.i(TAG,time);
               // LogUtils.i(TAG,"----onSure:"+TimeUtils.formatTime1(date.getTime()));

                String selectTime=time.split(" ")[0];
//                long currentTime= TimeUtils.getCurDate().getTime();
//                if (selectTime>currentTime){
//                    ToastUtil.show("选择的时间大于了现在的时间");
//                    return;
          //      }



                if (i==1){
                    time_ci_1_str=selectTime;
                   // ViewUtils.setTextViewStr(top_right_ci_tv,time_ci_1_str);
                    ViewUtils.setTextViewStr(top_right_ci_tv,TimeUtils.formatDateStampString0(getApplicationContext(),TimeUtils.parseFormatter3Time(time_ci_1_str).getTime()));
                }else if (i==2){
                    time_tian_1_str=selectTime;
                   // ViewUtils.setTextViewStr(top_right_tian_2_tv,time_tian_1_str);
                    ViewUtils.setTextViewStr(top_right_tian_2_tv,TimeUtils.formatDateStampString0(getApplicationContext(),TimeUtils.parseFormatter3Time(time_tian_1_str).getTime()));
                }else if (i==3){
                    time_tian_2_str=selectTime;
                   // ViewUtils.setTextViewStr(top_right_tian_4_tv,time_tian_2_str);
                    ViewUtils.setTextViewStr(top_right_tian_4_tv,TimeUtils.formatDateStampString0(getApplicationContext(),TimeUtils.parseFormatter3Time(time_tian_2_str).getTime()));
                }

                getDataFromNet();
            }
        }, "1945-01-01 00:00", time);
       // datePicker.setSelectedCalender("1991-06-13");
        datePicker.showSpecificTime(false); //显示时和分
        datePicker.setIsLoop(false);
        datePicker.setDayIsLoop(true);
        datePicker.setMonIsLoop(true);



        String showDate=date;
        if (i==1){
            showDate=time_ci_1_str.split(" ")[0];
        }else if (i==2){
            showDate=time_tian_1_str.split(" ")[0];
        }else if (i==3){
            showDate=time_tian_2_str.split(" ")[0];
        }

        //datePicker.show(date);
        datePicker.show(showDate);
      //  datePicker.setBackgroundColor(Color.parseColor("#ff0000"));







//        DatePickDialog dialog = new DatePickDialog(this);
//        //设置上下年分限制
//        dialog.setYearLimt(50);
//        //设置类型
//        dialog.setType(DateType.TYPE_YMD);
//
//        //设置选择回调
//        dialog.setOnChangeLisener(new OnChangeLisener() {
//            @Override
//            public void onChanged(Date date,int index) {
//                LogUtils.i(TAG,"----onChanged : "+ TimeUtils.formatTime1(date.getTime()));
//            }
//        });
//        //设置点击确定按钮回调
//        dialog.setOnSureLisener(new OnSureLisener() {
//            @Override
//            public void onSure(Date date,int index) {
//                LogUtils.i(TAG,"----onSure:"+TimeUtils.formatTime1(date.getTime()));
//
//                long selectTime=date.getTime();
//                long currentTime= TimeUtils.getCurDate().getTime();
//                if (selectTime>currentTime){
//                    ToastUtil.show("选择的时间大于了现在的时间");
//                    return;
//                }
//
//
//
//                if (i==1){
//                    time_ci_1_str=TimeUtils.formatTime3(date.getTime());
//                    ViewUtils.setTextViewStr(top_right_ci_tv,time_ci_1_str);
//                }else if (i==2){
//                    time_tian_1_str=TimeUtils.formatTime3(date.getTime());
//                    ViewUtils.setTextViewStr(top_right_tian_2_tv,time_tian_1_str);
//                }else if (i==3){
//                    time_tian_2_str=TimeUtils.formatTime3(date.getTime());
//                    ViewUtils.setTextViewStr(top_right_tian_4_tv,time_tian_2_str);
//                }
//
//
//                getDataFromNet();
//            }
//        });
//       // dialog.setStartDate(new Date(1997-1900,6-1,23));
//        dialog.setStartDate(new Date(System.currentTimeMillis()));
//        dialog.show();


    }

    //弹出天次选择器
    private void showTianCiDialog() {
        TianCiPickDialog dialog = new TianCiPickDialog(this);
        //设置点击确定按钮回调
        dialog.setOnSureLisener(new OnSureLisener() {
            @Override
            public void onSure(Date date, int index) {
                LogUtils.i(TAG,"----onSure:"+index);
                currentDisplayStyle=index;
                updateTopLayout();
                getDataFromNet();
            }
        });
        dialog.show();
        dialog.setCurrentIndex(currentDisplayStyle);

    }




    //从后台拉取数据
    private void getDataFromNet(){
        String fromTime = null;
        String endTime = null;

        if (currentDisplayStyle==0){//天
            fromTime=time_tian_1_str+" 00:00:00";
            endTime=time_tian_2_str+" 23:59:59";
        }else if (currentDisplayStyle==1){//次

            fromTime=time_ci_1_str+" 00:00:00";
            endTime=time_ci_1_str+" 23:59:59";
        }

        Date fromDate = TimeUtils.parseFormatter1Time(fromTime);
        Date toDate = TimeUtils.parseFormatter1Time(endTime);

        if (fromDate.getTime()>=toDate.getTime()){
          //  ToastUtil.show(getString(R.string.tow_time_no_right));
            chartViewClear();
            extendValues2Non();
            clearArrowIv();
            return;
        }

        final String finalEndTime = endTime;
        final String finalFromTime = fromTime;
        NetUtils.getInstance().getBloodPressureData2(this, 0, 500, fromTime, endTime, new HttpResponse<GetBloodPressureData2>() {
            @Override
            public void result(boolean isRequestSuccess, String requestDes, GetBloodPressureData2 getBloodPressureData2, String s) {
                LogUtils.i(TAG,"fromTime = "+ finalFromTime +"-------endTime = "+ finalEndTime);
                LogUtils.i(TAG,"s----->"+s);
                if (!isRequestSuccess){
                    chartViewClear();
                    extendValues2Non();
                    clearArrowIv();
                    return;
                }

                if (getBloodPressureData2.getResultCode()==0){
                    disCharView(getBloodPressureData2);
                }else {
                    chartViewClear();
                    extendValues2Non();
                    clearArrowIv();
                }

            }
        });




    }


    private void chartViewClear(){
        if (chartview_ss_sz!=null){
            chartview_ss_sz.clear();
        }
        if (chartview_maibo!=null){
            chartview_maibo.clear();
        }
    }

    private void disCharView(GetBloodPressureData2 getBloodPressureData2) {



        if (getBloodPressureData2!=null&&getBloodPressureData2.getResultData()!=null
                &&getBloodPressureData2.getResultData().getData()!=null
                &&getBloodPressureData2.getResultData().getData().size()>0){


            //x轴坐标对应的数据
            List<String> oneXValue = new ArrayList<>();

            //y轴坐标对应的数据
            List<Integer> oneYValue = new ArrayList<>();
            //折线对应的数据
            Map<String, Integer> oneValue = new HashMap<>();
            Map<String, Integer> oneValue2 = new HashMap<>();
            Map<String, Integer> twoValue = new HashMap<>();

            int maxVaue=0;


            for (int i=0;i<getBloodPressureData2.getResultData().getData().size();i++){

                GetBloodPressureData2.ResultDataBean.DataBean bean=getBloodPressureData2.getResultData().getData().get(i);
                if (bean==null|| StringUtils.isEmpty(bean.getTestDate())){
                    continue;
                }

               // String disTime=StringUtils.subString(bean.getTestDate(),11,16);

               // String disTime1=StringUtils.subString(bean.getTestDate(),5,10);
               // String disTime2=StringUtils.subString(bean.getTestDate(),11,16);
              //  String disTime2=StringUtils.subString(bean.getTestDate(),10,16);
               // String disTime=disTime1+" "+disTime2;
                String disTime=bean.getTestDate();

                int ss=bean.getSystolic();

                if (ss>maxVaue){
                    maxVaue=ss;
                }



                int sz=bean.getDiastolic();
                int mb=bean.getPulse();



                oneXValue.add(disTime);
                oneValue.put(disTime, ss);//60--240
                oneValue2.put(disTime, sz);//60--240
                twoValue.put(disTime, mb);//60--240



            }


            int h=7;
            if (maxVaue>0){
                h=maxVaue/30+3;
            }

            for (int i = 0; i < h; i++) {//Y轴的刻度值
                oneYValue.add(i *30);
            }


            if (chartview_ss_sz!=null){
                chartview_ss_sz.setValue(oneValue,oneValue2,oneXValue,oneYValue);
            }

            if (chartview_maibo!=null){
                chartview_maibo.setValue(twoValue,null,oneXValue,oneYValue);
            }

            int maxSystolic=getBloodPressureData2.getResultData().getMaxSystolic();
            int minSystolic=getBloodPressureData2.getResultData().getMinSystolic();
            int avgSystolic=getBloodPressureData2.getResultData().getAvgSystolic();

            int maxDiastolic=getBloodPressureData2.getResultData().getMaxDiastolic();
            int minDiastolic=getBloodPressureData2.getResultData().getMinDiastolic();
            int avgDiastolic=getBloodPressureData2.getResultData().getAvgDiastolic();

            int avgPulse=getBloodPressureData2.getResultData().getAvgPulse();
            int maxPulse=getBloodPressureData2.getResultData().getMaxPulse();
            int minPulse=getBloodPressureData2.getResultData().getMinPulse();


            disArrow(shsy_qushi_iv,getBloodPressureData2.getResultData().getData().get(0).getSystolic(),avgSystolic);
            disArrow(shzhy_qushi_iv,getBloodPressureData2.getResultData().getData().get(0).getDiastolic(),avgDiastolic);
            disArrow(maibo_qushi_iv,getBloodPressureData2.getResultData().getData().get(0).getPulse(),avgPulse);

            if (getBloodPressureData2.getResultData().getData().size()==1&&maibo_qushi_iv!=null){
                maibo_qushi_iv.setImageResource(0);
            }


            disExtendValues(minSystolic+NON,maxSystolic+NON,avgSystolic+NON,
                    minDiastolic+NON,maxDiastolic+NON,avgDiastolic+NON,
                    minPulse+NON,maxPulse+NON,avgPulse+NON);




        }else {
            chartViewClear();
            extendValues2Non();
            clearArrowIv();
        }


    }

    private void disArrow(ImageView imageView,int currentValue,int avgValue){
        if (imageView==null)return;
        if (currentValue<avgValue){
            imageView.setImageResource(R.drawable.ipm_jian);
        }else if (currentValue==avgValue){
            imageView.setImageResource(R.drawable.ipm_ic_hold);
        }else {
            imageView.setImageResource(R.drawable.ipm_ic_add);
        }
    }
}
